package jtg.generator;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.RandomStringUtils;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.Random;

public class RandomGenerator {
    static Random random = new Random();

    private String clsPath;
    private String clsName;
    private String mtdName;

    public RandomGenerator(String className, String methodName) {
        String defaultClsPath = System.getProperty("user.dir") + File.separator + "target" + File.separator + "test-classes";
        new RandomGenerator(defaultClsPath, className, methodName);
    }

    public RandomGenerator(String classPath, String className, String methodName) {
        this.clsPath = classPath;
        this.mtdName = methodName;
        this.clsName = className;
    }

    //随机生成类的一个方法的参数 这里处理方法中参数类型在  Java 基本类型、String、数组、枚举类型 中的
    public Object generate() throws Exception {
        // 获取目标类和方法信息
        Class<?> clazz = Class.forName(clsName); // 替换为目标类的实际类名
        Method[] methods = clazz.getMethods(); // 获取目标类的方法
        Method tmethod = null;
        for (Method m : methods) {
            if (m.getName().equals(mtdName))
                tmethod = m;
        }
        Object[] gens = new Object[0];
        if (tmethod != null) {
            Class<?>[] paraTypes = tmethod.getParameterTypes();
            gens = new Object[paraTypes.length];
            for (int i = 0; i < paraTypes.length; i++) {
                gens[i] = ranGenPara(paraTypes[i]);
            }
        }
        System.out.println(JSON.toJSONString(gens));
        return gens;
    }

    //随机生成方法中的一个参数
    private Object ranGenPara(Class<?> paraType) throws Exception, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Object gen = ranGenBasic(paraType);
        if (gen == null) {
            if (paraType.isArray()) {
                return ranGenArray(paraType);
            }
            else {
                //这里是参数类型为一个类
                String classname = paraType.toString();
                String classname1 = classname.substring(6);
                System.out.println("Class Name:"+classname1);
                Class<?> genClass = Class.forName(classname1);
                // 获取类的默认构造函数
                Constructor<?> constructor = genClass.getConstructor();
                constructor.setAccessible(true);
                // 使用默认构造函数实例化类对象
                Object obj = constructor.newInstance();
                // 设置一些默认值
                Field[] fields = genClass.getDeclaredFields();
                for (int i=0 ;i<fields.length;i++) {
                    Field field = fields[i];
                    // 设置属性的默认值（可以根据需要修改）
                    Class<?> type = field.getType();
                    Object objv = ranGenBasic(type);
//                    System.out.println("test111: "+objv);
                    field.setAccessible(true);
                    field.set(obj,objv);
                }
                return obj;
            }
        }
        return gen;
    }

    //随机生成数组
    public Object ranGenArray(Class<?> paraType) {
        Class<?> componentType = paraType.getComponentType();
        int len = (int) (Math.random() * 10);
        Object[] gens = new Object[len];
        for (int i = 0; i < gens.length; i++) {
            gens[i] = ranGenBasic(componentType);
        }
        return gens;
    }

    //随机生成Java基本类型
    public Object ranGenBasic(Class<?> paraType) {
        Object gen = null;
        if (paraType == int.class) {
            gen = randomInt();
            System.out.println("randomInt:" + gen);
        } else if (paraType == byte.class) {
            gen = randomByte();
            System.out.println("randomByte:" + gen);
        } else if (paraType == short.class) {
            gen = randomShort();
            System.out.println("randomShort:" + gen);
        } else if (paraType == long.class) {
            gen = randomLong();
            System.out.println("randomLong:" + gen);
        } else if (paraType == float.class) {
            gen = randomFloat();
            System.out.println("randomFloat:" + gen);
        } else if (paraType == double.class) {
            gen = randomDouble();
            System.out.println("randomDouble:" + gen);
        } else if (paraType == char.class) {
            gen = randomChar();
            System.out.println("randomChar:" + gen);
        } else if (paraType == boolean.class) {
            gen = randomBool();
            System.out.println("randomBool:" + gen);
        } else if (paraType == String.class) {
//            gen = RandomStringUtils.randomAlphanumeric(len);
            gen = randomString();
            System.out.println("randomString:" + gen);
        } else if (paraType.isEnum()) {
            //获取枚举类型 parameterType 的所有枚举常量，并将它们存储在一个数组
            Object[] enumConstants = paraType.getEnumConstants();
            //生成一个随机的数组索引值，然后从enumConstants数组中选择一个对应的枚举常量
            gen = enumConstants[randomInt(enumConstants.length)];
            System.out.println("randomEnum:" + gen);
        }
        return gen;
    }


    public static String randomString(){
        final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        int length = (int) (Math.random() * 20);
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(randomIndex));
        }
        return sb.toString();
    }

    public static byte randomByte() {
        byte[] byteArray = new byte[1]; // 生成长度为 1 的 byte 数组
        random.nextBytes(byteArray); // 生成随机的 byte 数组
        // 取出生成的随机 byte 值
        byte randomByte = byteArray[0];
        return randomByte;
    }

    public static short randomShort() {
        short randomShort = (short) (random.nextInt(Short.MAX_VALUE + 1) - Short.MAX_VALUE / 2);
        return randomShort;
    }

    public static int randomInt() {
        return random.nextInt();
    }

    public static int randomInt(int bound) {
        return random.nextInt(bound);
    }

    public static long randomLong() {
        return random.nextLong();
    }

    public static float randomFloat() {
        //随机生成最小浮点数和最大浮点数之间的浮点数
        float randomFloat = random.nextFloat() * 1000.0F;
        if (random.nextBoolean()) {
            randomFloat = randomFloat; // 正数
        } else {
            randomFloat = -randomFloat; // 负数
        }
        return randomFloat;
    }

    public static double randomDouble() {
        double randomDouble = random.nextDouble() * 1000.0;
        if (random.nextBoolean()) {
            randomDouble = randomDouble; // 正数
        } else {
            randomDouble = -randomDouble; // 负数
        }
        return randomDouble;
    }

    public static String ranStr(int len) {
        return RandomStringUtils.randomAlphanumeric(len);
    }

    public static char randomChar() {
        return (char) random.nextInt(65536);
    }

    public static boolean randomBool() {
        return random.nextBoolean();
    }

}
